package com.yike.common.base;

import com.google.protobuf.ServiceException;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

/**
 * Controller父类
 */
@Slf4j
public abstract class BaseController {


    /**
     * 获取请求数据
     *
     * @param request
     * @return
     */
    protected final String getBody(HttpServletRequest request) throws ServiceException {
        InputStreamReader in = null;
        try {
            in = new InputStreamReader(request.getInputStream(), StandardCharsets.UTF_8);
            StringBuffer bf = new StringBuffer();
            int len;
            char[] chs = new char[1024];
            while ((len = in.read(chs)) != -1) {
                bf.append(new String(chs, 0, len));
            }
            return bf.toString();
        } catch (Exception e) {
            log.error("请求头部取数据异常：{}", e);
            throw new ServiceException("无效的请求数据");
        } finally {
            if (null != in) {
                try {
                    in.close();
                } catch (Exception e) {
                    log.error("流关闭异常:{}", e);
                }
            }
        }
    }

}
